#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ChannelMap.h"

ChannelMap *channelMapInit(int32_t size)
{
    if (size <= 0)
    {
        return NULL;
    }
    ChannelMap *map = (ChannelMap *)malloc(sizeof(ChannelMap));
    if (!map)
    {
        return NULL;
    }
    map->list = (struct Channel **)calloc(size, sizeof(struct Channel *));
    if (!map->list)
    {
        free(map);
        return NULL;
    }
    map->size = size;
    return map;
}

void channelMapClear(ChannelMap *map)
{
    if (map != NULL)
    {
        for (int32_t i = 0; i < map->size; i++)
        {
            if (map->list[i] != NULL)
            {
                free(map->list[i]);
            }
        }
        free(map->list);
        map->list = NULL;
    }
    map->size = 0;
}

bool MakeMapRoom(ChannelMap *map, int32_t newSize, int32_t unitSize)
{
    if (!map || newSize <= 0 || unitSize <= 0)
    {
        return false;
    }

    if (map->size < newSize)
    {
        int32_t curSize = map->size;
        while (curSize < newSize)
        {
            curSize *= 2;
        }

        struct Channel **newList = (struct Channel **)realloc(map->list, unitSize * curSize);
        if (!newList)
        {
            return false;
        }
        map->list = newList;
        // memset(&map->list[map->size], 0, unitSize * (curSize - map->size));  &map->list[map->size] 可能指向未分配的内存，导致访问越界。
        memset(map->list + map->size, 0, unitSize * (curSize - map->size));
        map->size = curSize;
    }
    return true;
}
